package com.fsd.admin.service.impl;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import org.springframework.stereotype.Repository;

import com.fsd.core.bean.Tree;
import com.fsd.core.common.BusinessException;
import com.fsd.core.util.Config;
import com.fsd.core.util.ParametersUtil;

import org.apache.log4j.Logger;
import org.hibernate.Criteria;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;

import com.fsd.admin.model.A_Employee;
import com.fsd.admin.model.A_area;
import com.fsd.admin.service.A_areaService;
import com.fsd.admin.dao.A_areaDao;
import com.google.gson.Gson;

@Repository("a_areaServiceImpl")
public class A_areaServiceImpl extends MainServiceImpl<A_area, String> implements A_areaService{
    
    private static final Logger log = Logger.getLogger(A_areaServiceImpl.class);
    private String depict = "地域类别";
    
    @Resource(name = "a_areaDaoImpl")
	public void setBaseDao(A_areaDao a_areaDao) {
		super.setBaseDao(a_areaDao);
	}
	
	@Resource(name = "a_areaDaoImpl")
	private A_areaDao objectDao;
	
	private String checkLeaf(String fid){
		long num = objectDao.getCount("parentid = '"+ fid +"'", "deleted = '0'");
		if (num > 0)
			return "false";
		return "true";
	}
	
	private List<A_area> queryObjectListById(String fid){
		return objectDao.queryByHql("from A_area a where a.parentid = '"+ fid +"' and a.deleted = '0' order by sort asc");
	}
	
	/**
	 * 加载分页数据
	 * @param param
	 * @return
	 * @throws Exception
	 */
	public ParametersUtil getObjectPageList(ParametersUtil param) throws Exception{
		Criteria c = objectDao.createCriteria();
		c.add(Restrictions.eq("deleted", "0"));
		c.addOrder(Order.asc("sort"));
		if(param.getJsonData() != null && !"".equals(param.getJsonData())){
			Gson gs = new Gson();
			Map objectMap = gs.fromJson(param.getJsonData(), Map.class);
			if(objectMap.get("fid") != null && !"".equals(objectMap.get("fid"))){
				c.add(Restrictions.eq("parentid", objectMap.get("fid")));
			}
			if(objectMap.get("name") != null && !"".equals(objectMap.get("name"))){
				c.add(Restrictions.like("name", "%" + objectMap.get("name") + "%"));
			}
		}
		return objectDao.findPager(param , c);
	}
	
	/**
	 * 异步加载对象树
	 * @return
	 * @throws Exception
	 */
	public List<Tree> getAsyncObjectTree(String fid) throws Exception{
		List<Tree> treelist = new ArrayList<Tree>();
		List<A_area> list = this.queryObjectListById(fid);
		Tree menu = null;
		for (A_area obj : list) {
			menu = new Tree();
			menu.setId(obj.getId());
			menu.setText(obj.getName());
			menu.setLeaf(Boolean.valueOf(obj.getIsleaf()));
			treelist.add(menu);
		}
		return treelist;
	}
	
	/**
	 * 加载对象树
	 * @return
	 * @throws Exception
	 */
	public List<Tree> getObjectTree(String fid) throws Exception{
		List<A_area> list = objectDao.queryByHql("from A_area a where a.baseid = '"+ fid +"' and a.deleted = '0' order by sort asc");
		List<Tree> treelist = this.getObjectTree(fid, list);
		return treelist;
	}
	private List<Tree> getObjectTree(String fid, List<A_area> list) throws Exception{
		List<Tree> treelist = new ArrayList<Tree>();
		Tree node = null;
		for (A_area obj : list) {
			if (obj.getParentid().equals(fid)){
				node = new Tree();
				node.setId(obj.getId());
				node.setText(obj.getName());
				node.setLeaf(Boolean.valueOf(obj.getIsleaf()));
				if(!node.isLeaf()){
					node.setChildren(this.getObjectTree(obj.getId(), list));
				}
				treelist.add(node);
			}
			
		}
		return treelist;
	}
	
	/**
	 * 保存对象（添加、修改）
	 * @param obj
	 */
	public void saveObject(A_area obj , A_Employee employee) throws Exception{
		if(obj.getId() != null && !"".equals(obj.getId())){
			//修改
			A_area obj_old = objectDao.get(obj.getId());
			obj_old.setBaseid(obj.getBaseid());
			obj_old.setParentid(obj.getParentid());
			obj_old.setParentname(obj.getParentname());
			obj_old.setName(obj.getName());
			obj_old.setSymbol(obj.getSymbol());
			obj_old.setFullname(obj.getFullname());
			obj_old.setAdmincode(obj.getAdmincode());
			obj_old.setAreacode(obj.getAreacode());
			obj_old.setPostcode(obj.getPostcode());
			obj_old.setSort(obj.getSort());
			obj_old.setRemark(obj.getRemark());
			obj_old.setUpdatedate(this.getData());//设置修改日期
			obj_old.setUpdateemployeeid(employee.getId());//设置修改用户id
			obj_old.setUpdateemployeename(employee.getRealname());//设置修改用户姓名
			objectDao.update(obj_old);
		}else{
			//添加
			obj.setId(this.getUUID());//设置主键
			obj.setAdddate(this.getData());//设置添加日期
			obj.setAddemployeeid(employee.getId());//设置添加用户id
			obj.setAddemployeename(employee.getRealname());//设置添加用户姓名
			obj.setIsleaf("true");
			obj.setDeleted("0");//设置删除标志(0:正常 1：已删除)
			objectDao.save(obj);
			objectDao.executeHql("update A_area t set t.isleaf = 'false' where t.id = '" + obj.getParentid() + "'");
		}
		this.sysLogService.saveObject(Config.LOGTYPEBC, this.depict + obj.getId() + obj.getName(), employee, A_areaServiceImpl.class);
	}
	
	/**
	 * 删除对象
	 * @param parameters
	 */
	@SuppressWarnings("unchecked")
	public void delObject(ParametersUtil parameters) throws Exception{
		Gson gs = new Gson();
		Map objectMap = gs.fromJson(parameters.getJsonData(), Map.class);
		ArrayList<String> dir = (ArrayList<String>) objectMap.get("ids");
		String ids = "";
		String oid = "";
		for (String id : dir) {
			if (!ids.equals("")){
				ids += ",";
			}
			ids += "'" + id + "'";
			oid = id;
		}
		objectDao.executeHql("update A_area t set t.deleted = '1' where t.id in (" + ids + ")");
		A_area obj = objectDao.get(oid);
		if (obj != null){
			objectDao.executeHql("update A_area t set t.isleaf = '" + this.checkLeaf(obj.getParentid()) + "' where t.id = '" + obj.getParentid() + "'");
		}
	}
	
	/**
	 * 根据ID加载对象
	 * @param parameters
	 * @return
	 * @throws Exception
	 */
	public A_area getObjectById(ParametersUtil parameters) throws Exception{
		Gson gs = new Gson();
		Map objectMap = gs.fromJson(parameters.getJsonData(), Map.class);
		if(objectMap.get("id") == null && "".equals(objectMap.get("id"))){
			throw new BusinessException(depict + "获取缺少ID参数!");
		}
		A_area obj = objectDao.get(objectMap.get("id").toString());
		if(obj == null){
			throw new BusinessException(depict + "数据不存在!");
		}
		return obj;
	}
}
